Serialize and Deserialize Binary Tree

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

  1. 1
  2. / \
  3. 2 3
  4. / \
  5. 4 5

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Codec {
  11. // Encodes a tree to a single string.
  12. public String serialize(TreeNode root) {
  13. if (root == null) return null;
  14. String delim = "";
  15. StringBuilder sb = new StringBuilder();
  16. Stack<TreeNode> stack = new Stack<>();
  17. stack.push(root);
  18. // preorder traversal
  19. while (!stack.isEmpty()) {
  20. TreeNode node = stack.pop();
  21. sb.append(delim).append(node == null ? "#" : String.valueOf(node.val));
  22. delim = ",";
  23. if (node != null) {
  24. stack.push(node.right);
  25. stack.push(node.left);
  26. }
  27. }
  28. return sb.toString();
  29. }
  30. // Decodes your encoded data to tree.
  31. public TreeNode deserialize(String data) {
  32. if (data == null) return null;
  33. String[] list = data.split(",");
  34. // create the root node and push it to the stack
  35. TreeNode root = new TreeNode(Integer.valueOf(list[0]));
  36. Stack<TreeNode> stack = new Stack<>();
  37. stack.push(root);
  38. // direction flag
  39. boolean left = true;
  40. for (int i = 1; i < list.length; i++) {
  41. TreeNode node = list[i].equals("#") ? null : new TreeNode(Integer.valueOf(list[i]));
  42. if (left) {
  43. stack.peek().left = node;
  44. if (node == null) left = false;
  45. } else {
  46. stack.pop().right = node;
  47. if (node != null) left = true;
  48. }
  49. if (node != null) stack.push(node);
  50. }
  51. return root;
  52. }
  53. }
  54. // Your Codec object will be instantiated and called as such:
  55. // Codec codec = new Codec();
  56. // codec.deserialize(codec.serialize(root));